⚡️ Speed up function _get_constraint_vals_and_feasibility by 9%
#38
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 9% (0.09x) speedup for
_get_constraint_vals_and_feasibilityinoptuna/samplers/_gp/sampler.py⏱️ Runtime :
1.61 milliseconds→1.48 milliseconds(best of146runs)📝 Explanation and details
The optimization replaces the O(n²) list comprehension with validation approach with a single O(n) loop that builds the constraint list and validates lengths incrementally.
Key changes:
Single-pass processing: Instead of creating the full
_constraint_valslist first and then validating all lengths withany(), the optimized version processes trials one by one, checking constraint length consistency as it builds the list.Early validation: The length check happens immediately when processing each trial, allowing for early exit on the first inconsistent constraint length rather than processing all trials before validation.
Eliminated redundant iteration: The original code iterates through trials twice - once in the list comprehension and once in the
any()validation. The optimized version does both operations in a single loop.Performance benefits:
any()generator expression and reduces total iterations from 2n to nThe optimization is particularly effective for large-scale scenarios where constraint length validation fails early, as shown in the test cases where inconsistent constraint detection becomes dramatically faster.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_get_constraint_vals_and_feasibility-mhbenxu1and push.